package com.wing.purchase.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.product.model.response.ProductVO;
import com.wing.purchase.model.entity.PurchaseSignFor;
import com.wing.purchase.model.request.PurchaseSignForForm;
import com.wing.purchase.model.response.*;
import com.wing.purchase.service.PurchaseSignForProductService;
import com.wing.purchase.service.PurchaseSignForService;
import com.wing.utils.ExcelUtils;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.web.db.config.util.DynamicDataSource;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 采购签收管理
 *
 * @author xiayang
 */
@Slf4j
@Validated
@Api(value = "采购签收管理", tags = "#/purchase/purchaseSignFor")
@RestController("purchaseSignForController")
@RequestMapping("purchase/admin/purchaseSignFor")
@RequiredArgsConstructor
public class PurchaseSignForController {

    private final PurchaseSignForService purchaseSignForService;
    private final PurchaseSignForProductService purchaseSignForProductService;

    @ApiOperation(value = "查询所有采购签收", notes = "搜索")
    @GetMapping("/list")
    public PageResult<PurchaseSignForVO> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String signNo, String status, Integer filterStorageWorkComplete,String inventoryTypeCode,String workType,String startTime,String endTime) {
        Page<PurchaseSignForVO> pg = new Page<>(page, limit);
        Map<String, Object> params = new HashMap<>();
        // 排序
        if (StringUtils.isNotBlank(sort) && StringUtils.isNotBlank(order)) {
            params.put("sort", sort);
            params.put("order", order);
        }
        // 搜索
        if (StringUtils.isNotBlank(signNo)) {
            params.put("signNo", signNo);
        }
        if (StringUtils.isNotBlank(inventoryTypeCode)) {
            params.put("inventoryTypeCode", inventoryTypeCode);
        }
        if (null != filterStorageWorkComplete) {
            params.put("filterStorageWorkComplete", filterStorageWorkComplete);
        }
        if (null != status) {
            params.put("status", status);
        }

        if (StringUtils.isNotBlank(startTime)) {
            params.put("startCreateTime", startTime);
        }

        if (StringUtils.isNotBlank(endTime)) {
            params.put("endCreateTime", endTime);
        }


        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        params.put("databaseUser", databaseUser);

        if (StringUtils.isBlank(workType)) {
            Page<PurchaseSignForVO> list = purchaseSignForService.pageList4app(pg, params);
            return new PageResult<>(list.getRecords(), list.getTotal());
        }else{
            Page<PurchaseSignForVO> list = purchaseSignForService.pageListChange4app(pg, params);
            return new PageResult<>(list.getRecords(), list.getTotal());
        }
    }


    @ApiOperation(value = "添加采购签收", notes = "添加")
    @PostMapping("/add")
    public JsonResult add(@Validated(PurchaseSignForForm.Add.class) @RequestBody PurchaseSignForForm purchaseSignForForm) {
       /* if (purchaseSignForService.add(purchaseSignForForm) > 0) {
            return JsonResult.success("添加成功");
        }*/
        return purchaseSignForService.add(purchaseSignForForm);
    }

    @ApiOperation(value = "修改采购签收", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(PurchaseSignForForm.Update.class) @RequestBody PurchaseSignForForm purchaseSignForForm) {
        PurchaseSignFor purchaseSignFor = purchaseSignForService.getById(purchaseSignForForm.getId());
        if (purchaseSignFor == null) {
            return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
                .setEditable(PurchaseSignFor.class)
                .setIgnoreError(true)
                .setIgnoreNullValue(true);
        BeanUtil.copyProperties(purchaseSignForForm, purchaseSignFor, copyOptions);
        if (purchaseSignForService.update(purchaseSignFor)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }


    @ApiOperation(value = "删除采购签收", notes = "删除")
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable("id") Long purchaseSignForId) {
        if (purchaseSignForService.delete(purchaseSignForId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "确认采购签收", notes = "确认")
    @PostMapping("/confirm")
    public JsonResult confirm(Long id) {
        try {
            if (purchaseSignForService.confirm(id)) {
                return JsonResult.success("确认成功");
            }
            return JsonResult.fail("确认失败");
        } catch (BusinessException e) {
            log.info(e.getMessage());
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.info(e.getMessage());
            return JsonResult.fail(e.getMessage());
        }
    }

    @ApiOperation(value = "查询入库签收单")
    @GetMapping("/getDeliverySignInfo")
    public JsonResult<PurchaseSignForVO> getDeliverySignInfo(String signNo) {
        PurchaseSignForVO purchaseSignFor = purchaseSignForService.getDeliverySignInfo(signNo);
        if (purchaseSignFor == null) {
            return JsonResult.fail("签收单不存在");
        }
        if (!purchaseSignFor.getStatus().equals("2")) {
            return JsonResult.fail("签收单未确认");
        }
        Map<String, Object> params = new HashMap<>();
        params.put("purchaseSignForId", purchaseSignFor.getId());
        params.put("filterStorageWorkComplete", 1); // 是否过滤已入库完成的产品
        List<PurchaseSignForProductVO> signProductList = purchaseSignForProductService.list4app(params);
        if (signProductList.size() > 0) {
            for (PurchaseSignForProductVO purchaseSignForProductVO : signProductList) {
                 if(purchaseSignForProductVO.getInventoryType()==11){
                         purchaseSignForProductVO.setPurchaseQuantity(null);
                         purchaseSignForProductVO.setUnitName(null);
                     purchaseSignForProductVO.setRate(null);
                     purchaseSignForProductVO.setTaxPrice(null);
                     purchaseSignForProductVO.setPrice(null);
                     purchaseSignForProductVO.setTax(null);
                     purchaseSignForProductVO.setTotalAmount(null);
                  }
            }

            purchaseSignFor.setSignProductList(signProductList);
        } else {
            return JsonResult.fail("该采购入库签收单所有产品已签收入库完毕！");
        }
        return JsonResult.success(purchaseSignFor);
    }

    @ApiOperation(value = "查询签收单产品信息和签收的条码总数")
    @GetMapping("/getSignPackLabelNum")
    public JsonResult<InventoryJobLabelVO> getSignPackLabelNum(Long signProductDetailId) {
        InventoryJobLabelVO inventoryJobLabelVO = purchaseSignForService.getSignPackLabelNum(signProductDetailId);
        return JsonResult.success(inventoryJobLabelVO);
    }

    @ApiOperation(value = "查询料箱数据", notes = "搜索")
    @GetMapping("/getPalletBox")
    public JsonResult<PalletBoxListVO> getPalletBox(String code, Long warehouseId) {
        PalletBoxListVO palletBox = purchaseSignForService.getPalletBox(code, warehouseId);
        if (palletBox == null) {
            return JsonResult.fail("料箱不存在");
        }
        return JsonResult.success(palletBox);
    }

    @ApiOperation(value = "采购入库作业/扫描包装条码", notes = "搜索")
    @GetMapping("/getSignPackLabel")
    public JsonResult<PurchaseSignForProductLabelVO> getSignPackLabel(Long signId, String code, Integer inoutType, Long signProductDetailId) {
        PurchaseSignForProductLabelVO purchaseSignForProductLabelVO = purchaseSignForService.getSignPackLabel(signId, code, inoutType, signProductDetailId);
        if (purchaseSignForProductLabelVO == null) {
            return JsonResult.fail("未找到包装条码");
        }
        if (purchaseSignForProductLabelVO.getStatus().name().equals("inventoryIn")) {
            return JsonResult.fail("此包装条码已入库，请勿重复扫码");
        }
        return JsonResult.success(purchaseSignForProductLabelVO);
    }

    @ApiOperation(value = "查询库位数据", notes = "搜索")
    @GetMapping("/getShelfSpace")
    public JsonResult<WarehouseShelfSpaceVO> getShelfSpace(String code, Long warehouseId) {
        WarehouseShelfSpaceVO warehouseShelfSpace = purchaseSignForService.getShelfSpace(code, warehouseId);
        if (warehouseShelfSpace == null) {
            return JsonResult.fail("库位不存在");
        }
        return JsonResult.success(warehouseShelfSpace);
    }


    @ApiOperation(value = "导出")
    @GetMapping("/export")
    public void export(HttpServletResponse response,
                       @RequestParam(name = "signNo", required = false) String signNo,
                       @RequestParam(name = "startTime", required = false) String startTime,
                       @RequestParam(name = "endTime", required = false) String endTime ){
        List<PurchaseSignForExportVO> list = new ArrayList<>();

        Page<PurchaseSignForVO> pg = new Page<>(1, 999999);

        Map params = new HashMap();
        if(StringUtils.isNotBlank(signNo)){
            params.put("signNo", signNo);
        }
        if(StringUtils.isNotBlank(startTime)){
            params.put("startTime", startTime);
        }

        if(StringUtils.isNotBlank(endTime)){
            params.put("endTime", endTime);
        }

        String databaseUser = DynamicDataSource.USER_PREFIX;
        if (StringUtils.isNotBlank(DynamicDataSource.name.get())) {
            databaseUser = databaseUser + "-" + DynamicDataSource.name.get();
        }
        params.put("databaseUser", databaseUser);

        list = purchaseSignForService.exportList4app(pg,params);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
        String timestamp = sdf.format(new Date());
        // 生成带时间戳的文件名
        String fileName = "入库签收记录_" + timestamp;
        ExcelUtils.export(response,fileName,list, PurchaseSignForExportVO.class);
    }

}
